package pl.przewozy;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class MainActivity extends Activity {

    public static final String TAG = "LNOWAK";
    public static final String URL = "http://82.160.42.14/opoznienia/";
    private final Map<String, String> patterns = new HashMap<String, String>();
    private TextView txt_status;
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupUI();
        Document doc = new Document("");

        try {
            setupFilter();
            startDownload();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startDownload() {
        if (checkNetworkConnection())
        {
            txt_status.setText("Connecting...");
            try{
                new DownloadWebpageTask().execute(URL);
            } catch (Exception e) {
                e.printStackTrace();
                txt_status.setText("Connection TimeOut!");
                Toast.makeText(getApplicationContext(),"Connection TIMEOUT!",Toast.LENGTH_LONG);
            }
        } else {
            txt_status.setText("Check network connection...");
            Toast.makeText(getApplicationContext(), "Check Network Connection!", Toast.LENGTH_SHORT);
        }
    }

    private void setupUI() {
        txt_status = (TextView) findViewById(R.id.txt_status);
        webView = (WebView) findViewById(R.id.webView);
    }

    private void displayWebPage(Document doc) {
        if (doc != null)
            txt_status.setText("OK.");
        else
            txt_status.setText("CONNECTION TIMEOUT!");
        doc = Jsoup.parse(doc.html());
        String text = "";
        ArrayList<Schedule> schedules = getSchedules(doc);
        ArrayList<Schedule> filtered = filterData(schedules, patterns);
        text = formHtml(filtered);
        webView.loadData(text, "text/html", "UTF-8");
    }

    private ArrayList<Schedule> getSchedules(Document doc) {
        String text;
        ArrayList<Schedule> schedules = new ArrayList<Schedule>();
        for (Element table: doc.select("table")) {
           for (Element row: table.select("tr")) {
               text = "";
               for (Element td: row.select("td")) {
                   text += td.text() + "|";
               }
               try {
                   schedules.add(new Schedule(text));
               } catch (ParseException e) {
                   e.printStackTrace();
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
        }
        return schedules;
    }

    private void setupFilter() throws ParseException {
        //pociagi które mnie interesują
        patterns.put("pociąg", " ");
        patterns.put("60135", "08:05");
        patterns.put("76533/2", "08:18");
        patterns.put("pociag", "08:34 KD");
        patterns.put("60137/6", "08:45");
        patterns.put("76820/1", "09:30");
        patterns.put("46931/0", "09:41");
        patterns.put("14203", "test");
        patterns.put("6024", "test");
        patterns.put("66125", "test");
        patterns.put("36122/3", "test");
        patterns.put("88325", "test");
        patterns.put("15022/3", "test");
    }

    private ArrayList<Schedule> filterData(ArrayList<Schedule> schedules, Map<String, String> patterns) {
        ArrayList<Schedule> filtered = new ArrayList<Schedule>();
        for (Schedule sc : schedules) {
            checkEquality(patterns, filtered, sc);
        }
        return filtered;
    }

    private void checkEquality(Map<String, String> patterns, ArrayList<Schedule> filtered, Schedule sc) {
        Iterator iter = patterns.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if (sc.trainNo.equalsIgnoreCase((String) entry.getKey())) {
                filtered.add(sc);
            }
        }
    }

    private String formHtml(ArrayList<Schedule> schedules) {
        String text;
        text = "<table border=\"1\">";
        for ( Schedule sc: schedules ) {
            text +=  "<tr><td>"+ sc.trainNo + "</td>" +
                    "<td>" + sc.delay + "</td>" +
                    "<td>" + patterns.get(sc.trainNo) + "</td>" +
                    "<td>" + sc.updateTime + "</td>" +
                    "</tr>";
        }
        text += "</table>";
        return text;
    }

    private boolean checkNetworkConnection() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    public void refresh_clicked(View view) {
        startDownload();
    }

    // Uses AsyncTask to create a task away from the main UI thread. This task takes a
    // URL string and uses it to create an HttpUrlConnection. Once the connection
    // has been established, the AsyncTask downloads the contents of the webpage as
    // an InputStream. Finally, the InputStream is converted into a string, which is
    // displayed in the UI by the AsyncTask's onPostExecute method.
    private class DownloadWebpageTask extends AsyncTask<String, Void, Document> {
        @Override
        protected Document doInBackground(String... urls) {
            Document doc = new Document("");
            try {
                doc = Jsoup.connect(urls[0]).timeout(10*1000).get();
                Log.d(TAG, "CONNECTION OK!");
            } catch (IOException e) {
                Log.e(TAG, "CONNECTION ERROR!");
                e.printStackTrace();
            }
            return doc;
        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(Document result) {
            displayWebPage(result);
        }
    }
}
